const jwt = require('jsonwebtoken')
const {JWT_SECRET} = require('../utils')
const redis = require('../utils/redis')
const {getUserStatusServe, getUserById} = require('../serve/user.serve')
const {findWxUserByIdServe} = require('../serve/appletUser.serve')

const auth = async (ctx, next) => {
    const {authorization} = ctx.request.header
    console.log(ctx.method)
    if (!authorization) {
        ctx.status = 401
        return ctx.body = {
            status: '1',
            msg: '无权限'
        }
    }
    //1.判断token权限
    let user;
    const token = authorization.replace('Bearer ', '')
    try {
        user = jwt.verify(token, JWT_SECRET);
        ctx.state.user = user;
        if (ctx.method !== 'GET' && user.username === 'youke' && ctx.url !== '/user/layout') {
            throw({name: '游客'})
        }
        //1.1先根据解析出来的id获取当前用户是否存在或者状态，如果用户已经被删除或者账户被停用，就不用让他进行下一步了
        const currentUser = await getUserById(user.id, false)
        if (currentUser) {
            const userStatus = await getUserStatusServe(user.id)
            //1.2查看当前用户状态,如果已经被禁用了,如果redis还存着这个用户信息就根据id删掉
            if (!userStatus) {
                await redis.del(user.id)
                throw({name: 'noUser'})
            }
        } else {
            await redis.del(user.id)
            throw({name: 'noUser'})
        }
        const res = await redis.get(user.id)
        if (!res) {
            throw({name: 'noUser'})
        }

        //2.判断接口权限
        //先去redis根据用户id获取当前权限按钮
        const userInfo = await redis.get(user.id)
        if (userInfo) {
            ctx.state.permissionButtons = JSON.parse(userInfo).permissionButtons;
        } else {
            ctx.state.permissionButtons = []
        }
    } catch (err) {
        switch (err.name) {
            case 'TokenExpiredError':
                console.error('token以过期')
                // await removeUserTokenServe(user.id)
                ctx.status = 401
                return ctx.body = {
                    status: 1,
                    msg: '无权限'
                }
            case 'JsonWebTokenError':
                console.error('无效的token')
                ctx.status = 403
                return ctx.body = {
                    status: 1,
                    msg: '无权限'
                }
            case 'noUser':
                console.error('找不到token中用户id')
                ctx.status = 401
                return ctx.body = {
                    status: 1,
                    msg: '无权限'
                }
            case '游客':
                return ctx.body = {
                    status: 1,
                    msg: '游客仅支持查看数据'
                }
        }
    }
    await next()
}

const appletAuth = async (ctx, next) => {
    const {authorization} = ctx.request.header
    if (!authorization) {
        ctx.status = 401
        return ctx.body = {
            status: '1',
            msg: '无权限'
        }
    }

    let appletUser;
    //1.判断token权限
    const token = authorization.replace('Bearer ', '')
    try {
        appletUser = jwt.verify(token, JWT_SECRET);
        ctx.state.appletUser = appletUser;
        const res = await redis.get(`applet${appletUser.id}`)
        if (!res) {
            throw({name: 'noUser'})
        }
    } catch (err) {
        switch (err.name) {
            case 'TokenExpiredError':
                console.error('token以过期')
                // await redis.del(`applet${appletUser.id}`)
                ctx.status = 401
                return ctx.body = {
                    status: 1,
                    msg: '无权限'
                }
            case 'JsonWebTokenError':
                console.error('无效的token')
                ctx.status = 403
                return ctx.body = {
                    status: 1,
                    msg: '无权限'
                }
            case 'noUser':
                console.error('找不到token中用户id')
                ctx.status = 401
                return ctx.body = {
                    status: 1,
                    msg: '无权限'
                }
        }
    }
    await next()
}

const wxAppletAuth = async (ctx, next) => {
    const {authorization} = ctx.request.header
    if (!authorization) {
        ctx.status = 401
        return ctx.body = {
            status: '1',
            msg: '无权限'
        }
    }

    let wxAppletUser;
    //1.判断token权限
    const token = authorization.replace('Bearer ', '')
    try {
        wxAppletUser = jwt.verify(token, JWT_SECRET);
        ctx.state.appletUser = wxAppletUser;
        // 用token解析出的id查询数据库中是否有该id的用户
        const wxUser = await findWxUserByIdServe({id: wxAppletUser.id})
        if (!wxUser) {
            throw({name: 'noUser'})
        }
        if (!wxUser.token) {
            throw({name: 'JsonWebTokenError'})
        }
    } catch (err) {
        switch (err.name) {
            case 'TokenExpiredError':
                console.error('token以过期')
                // await redis.del(`applet${appletUser.id}`)
                ctx.status = 401
                return ctx.body = {
                    status: 1,
                    msg: '无权限'
                }
            case 'JsonWebTokenError':
                console.error('无效的token')
                ctx.status = 403
                return ctx.body = {
                    status: 1,
                    msg: '无权限'
                }
            case 'noUser':
                console.error('找不到token中用户id')
                ctx.status = 401
                return ctx.body = {
                    status: 1,
                    msg: '无权限'
                }
        }
    }
    await next()
}

const btnAuth = (ctx, btnPermission) => {
    return ctx.state.permissionButtons.includes(btnPermission)
}

module.exports = {
    auth, btnAuth,
    appletAuth,
    wxAppletAuth
}
